package com.link.base.base.email.emailutils;

import com.link.core.cllog.LCLogger;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

/**
 * @author weixuan
 */
public class UploadImgServlet extends HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public UploadImgServlet() {
        super();
    }

    @Override
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = request.getRealPath("/image");
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 文件名称
        String fileName = "";
        /**上传文件处理内容**/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        // 处理中文问题
        sfu.setHeaderEncoding("UTF-8");
        // 限制文件大小
        sfu.setSizeMax(5 * 1024 * 1024);
        try {
            // 解码请求
            List<FileItem> fileItems = sfu.parseRequest(request);
            for (FileItem fi : fileItems) {

                fileName = UUID.randomUUID() + fi.getName().substring(fi.getName().lastIndexOf("."), fi.getName().length());
                fi.write(new File(path, fileName));
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        /**********************/

        //获取图片url地址
        String imgUrl = "http://localhost:8080/image/" + fileName;
        response.setContentType("text/text;charset=utf-8");
        PrintWriter out = response.getWriter();
        //返回url地址
        out.print(imgUrl);
        out.flush();
        out.close();
    }

    @Override
    public void init() throws ServletException {

    }
}
